# -*- coding=utf-8 -*-

import time


def get_message_class(event_num):
    event_num_dict = {
        26: 'system fault',
        8: 'fault gantry',
        9: 'gantry at standstill',
        11: 'measuring machine fault',
        15: 'operation fault',
        21: 'pre/post transport system fault',
        22: 'coolant fault',
        25: 'fire alarm',
        33: 'special tool change',
        34: 'waiting for maintenance',
        41: 'services fault',
        70: 'overflow',
        31: 'repair in break',
        35: 'repair',
        19: 'outlet occupied',
        44: 'manual outlet occupied',
        20: 'empty intake',
        43: 'manual empty intake',
        1: 'no reason',
        18: 'waiting for tool change',
        23: 'switched off',
        39: 'manual empty intake',
        37: 'planned maintenance',
        38: 'tool change',
        40: 'team meeting',
        42: 'manual refurbish',
        52: 'machine cleaning',
        69: 'break',
        71: 'start up machine',
        74: 'waiting for subcomponents',
        3: 'technology trial',
        4: 'rework',
        64: 'rework',
        68: 'rework',
        16: 'quality check in process',
        46: 'quality check in process',
        17: 'waiting for first part inspection',
        45: 'first part inspection',
        24: 'disabled',
        63: 'setting-up',
        72: 'automatic setting-up',
        36: 'miscellaneous',
        47: 'miscellaneous',
        48: 'miscellaneous',
        49: 'miscellaneous',
        50: 'miscellaneous',
        51: 'miscellaneous',
        2: 'production',
        5: 'production',
        6: 'production',
        7: 'production',
        10: 'production',
        12: 'production',
        13: 'production',
        14: 'production',
        65: 'production',
        66: 'production',
        67: 'production'
    }
    return event_num_dict.get(event_num) if event_num in event_num_dict else 'unknown'


# 指定时间与当前时间的差，转换成小时的形式
def convert_to_shift_hour(time_str):
    last_time_tuple = time.strptime(time_str, '%Y-%m-%d %H:%M:%S')
    last_time_stamp = time.mktime(last_time_tuple)
    cur_time_stamp = time.time()
    shift_sec = int(cur_time_stamp - last_time_stamp)
    hour = int(shift_sec / 3600)
    minute = int((shift_sec - 3600 * hour) / 60)
    if hour > 99:
        hour = 99
        minute = 99
    hour = str(hour) if hour > 9 else '0' + str(hour)
    minute = str(minute) if minute > 9 else '0' + str(minute)
    return hour + ':' + minute


def get_shift_time_range(items):
    from .util import string_to_timestamp
    shift_time_dict = {
        'StartTime1': 0,
        'EndTime1': 0,
        'StartTimestamp1': 0,
        'EndTimestamp1': 0,
        'StartTime2': 0,
        'EndTime2': 0,
        'StartTimestamp2': 0,
        'EndTimestamp2': 0,
        'StartTime3': 0,
        'EndTime3': 0,
        'StartTimestamp3': 0,
        'EndTimestamp3': 0
    }
    for item in items:
        if item['SCHICHT'] == "1":
            shift_time_dict['StartTime1'] = time.strftime('%F %T', item['SCHICHT_VON'])
            shift_time_dict['EndTime1'] = time.strftime('%F %T', item['SCHICHT_BIS'])
            shift_time_dict['StartTimestamp1'] = string_to_timestamp(shift_time_dict['StartTime1']) \
                if 'StartTime1' in shift_time_dict.keys() else 0
            shift_time_dict['EndTimestamp1'] = string_to_timestamp(shift_time_dict['EndTime1']) \
                if 'EndTimestamp1' in shift_time_dict.keys() else 0
        elif item['SCHICHT'] == "2":
            shift_time_dict['StartTime2'] = time.strftime('%F %T', item['SCHICHT_VON'])
            shift_time_dict['EndTime2'] = time.strftime('%F %T', item['SCHICHT_BIS'])
            shift_time_dict['StartTimestamp2'] = string_to_timestamp(shift_time_dict['StartTime2']) \
                if 'StartTime2' in shift_time_dict.keys() else 0
            shift_time_dict['EndTimestamp2'] = string_to_timestamp(shift_time_dict['EndTime2']) \
                if 'EndTimestamp2' in shift_time_dict.keys() else 0
        elif item['SCHICHT'] == "3":
            shift_time_dict['StartTime3'] = time.strftime('%F %T', item['SCHICHT_VON'])
            shift_time_dict['EndTime3'] = time.strftime('%F %T', item['SCHICHT_BIS'])
            shift_time_dict['StartTimestamp3'] = string_to_timestamp(shift_time_dict['StartTime3']) \
                if 'StartTime3' in shift_time_dict.keys() else 0
            shift_time_dict['EndTimestamp3'] = string_to_timestamp(shift_time_dict['EndTime3']) \
                if 'EndTimestamp3' in shift_time_dict.keys() else 0
    current_timestamp = time.time()
    start_time_str = ''
    end_time_str = ''
    if shift_time_dict['StartTimestamp1'] <= current_timestamp <= shift_time_dict['EndTimestamp1']:
        start_time_str = shift_time_dict['StartTime1']
        end_time_str = shift_time_dict['EndTime1']
    elif shift_time_dict['StartTimestamp2'] <= current_timestamp <= shift_time_dict['EndTimestamp2']:
        start_time_str = shift_time_dict['StartTime2']
        end_time_str = shift_time_dict['EndTime2']
    elif shift_time_dict['StartTimestamp3'] <= current_timestamp <= shift_time_dict['EndTimestamp3']:
        start_time_str = shift_time_dict['StartTime3']
        end_time_str = shift_time_dict['EndTime3']
    return {
        'start_time_str': start_time_str,
        'end_time_str': end_time_str
    }


def get_production_volume_by_range(db_eng, op, baz, time_start, time_end=None):
    sql = "SELECT COUNT(*) cnt FROM ARCHIV_WORKLOG WHERE FERTEINR_OP='" \
          + op + "' AND FERTEINR_ZN  = 1" \
                 " AND FERTEINR_BAZ ='" + \
          baz + "' AND VORRICHTUNG >=0 AND UEBERLAUF<99" \
                " AND BEARB_DATUM >= TO_DATE('" + time_start + "', 'YYYY-MM-DD HH24:MI:SS')"
    if time_end is not None:
        sql += " AND BEARB_DATUM < TO_DATE('" + time_end + "', 'YYYY-MM-DD HH24:MI:SS')"
    # print(sql)
    result_proxy = db_eng.execute(sql)
    row = result_proxy.fetchone()
    return row['cnt']


def format_hour_str(hour_str):
    return hour_str[0:2] + ':' + hour_str[2:4] + ':' + hour_str[4:6] if hour_str is not None else False


# todo 20160930 国庆回来继续
def get_shift_time(date_num, line_name, date_format='%Y%m%d', reformat=False):
    from app.model.mo_nep_pss import StandARDSchichtModelle, \
        StandARDSchichten, \
        StandardModelle
    from app import db
    from sqlalchemy import and_, func, distinct, select, desc
    # # if line_name == 'Z6':
    # #     items = Z6SchichtKalenderGrossAnzeige.query \
    # #         .filter(Z6SchichtKalenderGrossAnzeige.NG6SK_DATUM == date_num) \
    # #         .all()
    # # else:
    # #     items = SchichtKalenderGrossAnzeige.query \
    # #         .filter(SchichtKalenderGrossAnzeige.NG6SK_DATUM == date_num) \
    # #         .all()
    #
    # date_tuple = time.strptime(date_num, '%Y%m%d')
    # date_str = time.strftime('%F 00:00:00', date_tuple)
    # items = SchichtKalender.query \
    #     .filter(and_(SchichtKalender.LINIE_KZ == line_name,
    #                  SchichtKalender.FB_OPERATION == 'AFO010',
    #                  SchichtKalender.DATUM == func.TO_DATE(date_str, 'YYYY-MM-DD HH24:MI:SS'))) \
    #     .all()
    # step 1 : 从 STANDARDSCHICHTMODELLE 表中获取小于等于当天的 SS_ID 最后一值
    # step 2 : 通过 SS_ID 从 STANDARDMODELLE 表中 获取 MD_ID、MODELL_NR、PROD_VON、PROD_BIS、PROG_STUECK
    # step 3 : 通过 MD_ID 从 STANDARDSCHICHTEN 表中 获取 当天使用的 Vorgabe 值
    # step 4 : 组织需要的数据
    items = []
    # do step 1
    # 获取明天的起始时间
    date_tuple = time.strptime(date_num, date_format)
    day_base_str = time.strftime('%Y-%m-%d', date_tuple)
    today_time_stamp = time.mktime(date_tuple)
    tomorrow_time_stamp = today_time_stamp + 3600 * 24
    tomorrow_time_tuple = time.localtime(tomorrow_time_stamp)
    tomorrow_date_str = time.strftime('%F 00:00:00', tomorrow_time_tuple)
    tomorrow_base_str = time.strftime('%Y-%m-%d', tomorrow_time_tuple)
    qry_row = db.session.query(StandARDSchichtModelle.SS_ID).filter(
        and_(StandARDSchichtModelle.LINIE_KZ == line_name, StandARDSchichtModelle.GUELTIG_VON < func.TO_DATE(tomorrow_date_str, 'YYYY-MM-DD HH24:MI:SS'))
    ).order_by(desc(StandARDSchichtModelle.SS_ID)).first()
    if qry_row is not None:
        ss_id = qry_row[0]
        # do step 2
        qry_row = db.session.query(StandardModelle).filter(
            and_(StandardModelle.SS_ID == ss_id, StandardModelle.MODELL_NR > 0)
        ).all()
        day_of_week = time.strftime('%w', date_tuple)
        day_of_week = day_of_week if int(day_of_week) > 0 else '7'
        if qry_row is not None:
            modelle_dict = {}
            for row in qry_row:
                md_id = row.MD_ID
                modell_nr = row.MODELL_NR
                modelle_dict[modell_nr] = row
                # do step 3
                schicht_items = db.session.query(StandARDSchichten).filter(
                    and_(
                        StandARDSchichten.MD_ID == md_id,
                        StandARDSchichten.TAG == day_of_week
                    )
                ).all()
                from_time = format_hour_str(row.PROD_VON)
                to_time = format_hour_str(row.PROD_BIS)
                if schicht_items is not None:
                    for schicht_item in schicht_items:
                        start_struct_time = False
                        end_struct_time = False
                        if from_time:
                            start_time = day_base_str + ' ' + format_hour_str(row.PROD_VON)
                            start_struct_time = time.strptime(start_time, '%Y-%m-%d %H:%M:%S')
                        if to_time:
                            if schicht_item.SCHICHT == '3':
                                end_time = tomorrow_base_str + ' ' + format_hour_str(row.PROD_BIS)
                            else:
                                end_time = day_base_str + ' ' + format_hour_str(row.PROD_BIS)
                            end_struct_time = time.strptime(end_time, '%Y-%m-%d %H:%M:%S')
                        item_dict = {
                            'SCHICHT': schicht_item.SCHICHT,
                            'SS_ID': ss_id,
                            'MD_ID': md_id,
                            'MODELL_NR': modell_nr,
                            'SCHICHT_VON': start_struct_time,
                            'SCHICHT_BIS': end_struct_time,
                            'PROG_STUECK': row.PROG_STUECK
                        }
                        items.append(item_dict)
            if line_name == 'G6' and day_of_week == '5':
                schicht_list = []
                for (item_key, item_val) in enumerate(items):
                    if item_val['SCHICHT'] == '1' or item_val['SCHICHT'] == '2':
                        schicht_list.append(item_val['SCHICHT'])
                        # G6 每周五从 5、6 里取数据
                        mid_idx = str(int(item_val['SCHICHT']) + 4)
                        # print('&&&&&&&&&&&&&&&&&&&&&&&&&')
                        # print(mid_idx)
                        if mid_idx in modelle_dict:
                            mid_item = modelle_dict[mid_idx]
                            ########## TMP ##########
                            from_time = format_hour_str(mid_item.PROD_VON)
                            to_time = format_hour_str(mid_item.PROD_BIS)
                            # from_time = format_hour_str('083000')
                            # to_time = format_hour_str('170000')
                            ########## TMP ##########
                            start_struct_time = False
                            end_struct_time = False
                            if from_time:
                                start_time = day_base_str + ' ' + from_time
                                start_struct_time = time.strptime(start_time, '%Y-%m-%d %H:%M:%S')
                            if to_time:
                                end_time = day_base_str + ' ' + to_time
                                end_struct_time = time.strptime(end_time, '%Y-%m-%d %H:%M:%S')
                            item_val['SCHICHT_VON'] = start_struct_time
                            item_val['SCHICHT_BIS'] = end_struct_time
                            ########## TMP ##########
                            item_val['PROG_STUECK'] = mid_item.PROG_STUECK
                            item_val['SOLL_STUECK'] = mid_item.SOLL_STUECK
                            # item_val['PROG_STUECK'] = 0
                            # item_val['SOLL_STUECK'] = 0
                            ########## TMP ##########
                            items[item_key] = item_val
                        else:
                            del items[item_key]

                # 特殊处理，如果SCHICHT的值1或2不存在，但preseting的5，6却有值
                # 需要特殊处理的列表
                special_list = ['5', '6']
                for special_val in special_list:
                    sp_val = str(int(special_val) - 4)
                    if special_val in modelle_dict and sp_val not in schicht_list:
                        sp_dict = {}
                        mid_item = modelle_dict[special_val]
                        from_time = format_hour_str(mid_item.PROD_VON)
                        to_time = format_hour_str(mid_item.PROD_BIS)
                        start_struct_time = False
                        end_struct_time = False
                        if from_time:
                            start_time = day_base_str + ' ' + from_time
                            start_struct_time = time.strptime(start_time, '%Y-%m-%d %H:%M:%S')
                        if to_time:
                            end_time = day_base_str + ' ' + to_time
                            end_struct_time = time.strptime(end_time, '%Y-%m-%d %H:%M:%S')
                        sp_dict['SCHICHT'] = sp_val
                        sp_dict['SCHICHT_VON'] = start_struct_time
                        sp_dict['SCHICHT_BIS'] = end_struct_time
                        sp_dict['PROG_STUECK'] = mid_item.PROG_STUECK
                        sp_dict['SOLL_STUECK'] = mid_item.SOLL_STUECK
                        items.append(sp_dict)
    if reformat is True:
        _tmp_items = [0, 0, 0]
        _i = 0
        for item in items:
            if 'SCHICHT' in item:
                obj = {
                    'from': time.strftime('%H:%M:%S', item['SCHICHT_VON']),
                    'to': time.strftime('%H:%M:%S', item['SCHICHT_BIS']),
                    'shiftNum': int(item['SCHICHT'])
                }
                _tmp_items[_i] = obj
            _i = _i + 1
        items = _tmp_items
    return items


def get_week_day_total_hours(db_engine, op, baz, today_date_str, line_name):
    from .util import get_week_first_date_str
    date_tuple = time.strptime(today_date_str, '%Y-%m-%d')
    week_day_number = int(time.strftime('%w', date_tuple))
    week_total_hour = 0
    if week_day_number == 0:
        week_day_number = 7
    for i in range(1, week_day_number + 1):
        date_str = get_week_first_date_str(today_date_str, i)
        day_shift_list = get_shift_time(date_str, line_name, '%Y-%m-%d', True)
        # print(date_str)
        # print(day_shift_list)
        for day_shift_item in day_shift_list:
            if type(day_shift_item) is dict:
                time_start_str = day_shift_item['from']
                start_hour_int = int(time_start_str[0:2])
                time_end_str = day_shift_item['to']
                end_hour_int = int(time_end_str[0:2])
                if start_hour_int < end_hour_int:
                    date_time_start_str = date_str + ' ' + time_start_str
                    date_time_end_str = date_str + ' ' + time_end_str
                else:
                    date_time_start_str = date_str + ' ' + time_start_str
                    after_date_timestamp = time.mktime(time.strptime(date_str, '%Y-%m-%d')) + 86400
                    after_date_str = time.strftime('%Y-%m-%d', time.localtime(after_date_timestamp))
                    date_time_end_str = after_date_str + ' ' + time_end_str
                pro_volume = get_production_volume_by_range(db_engine, op, baz, date_time_start_str, date_time_end_str)
                from_timestamp = time.mktime(time.strptime(date_time_start_str, '%Y-%m-%d %H:%M:%S'))
                to_timestamp = time.mktime(time.strptime(date_time_end_str, '%Y-%m-%d %H:%M:%S'))
                now_timestamp = time.time()
                if type(pro_volume) is int and pro_volume > 0:
                    if from_timestamp < now_timestamp < to_timestamp:
                        week_total_hour += int(now_timestamp - from_timestamp)
                    else:
                        week_total_hour += int(to_timestamp - from_timestamp)
    return week_total_hour / 3600
